package com.jthinker.service.impl;

import com.jthinker.bean.enu.SortOrder;
import com.jthinker.bean.vo.QueryResult;
import com.jthinker.bean.vo.SearchFilter;
import com.jthinker.dao.BaseDao;
import com.jthinker.dao.PostDao;
import com.jthinker.service.CommonService;
import com.jthinker.service.PostService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Map;

/**
 * User: Gang Chen
 * Date: 2015/4/13 21:48
 */
@Service
public class PostServiceImpl implements PostService
{
    private static final Logger LOGGER = LoggerFactory.getLogger(PostService.class);

    @Resource
    private BaseDao baseDao;

    @Resource
    private CommonService commonService;

    @Resource
    private PostDao postDao;

    @Override
    public Map<String, Object> read(Serializable id)
    {
        return postDao.read(id);
    }

    @Override
    public QueryResult<Map<String, Object>> queryList(SearchFilter filter)
    {
        filter.setSort("post_date");
        filter.setSortOrder(SortOrder.DESC);
        return commonService.querySql(filter, "SELECT id,title,excerpt,content,post_date,category_id FROM blog_post");
    }

    @Override
    public QueryResult<Map<String, Object>> queryGrid(SearchFilter filter)
    {
        String sql = ""
                + "SELECT p.id,p.title,u.nickname uname,c.name cname,p.comment_count,p.post_date  "
                + "FROM blog_post p  "
                + "LEFT JOIN sys_user u ON p.user_id=u.id  "
                + "LEFT JOIN blog_category c ON c.id=p.category_id";
        return commonService.querySql(filter, sql);
    }

    @Override
    public void create(Map<String, Object> post) throws Exception
    {
        try
        {
            postDao.create(post);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            LOGGER.error("Exception: {}", e);
        }
    }

    @Override
    public void update(Map<String, Object> post, Serializable id) throws Exception
    {
        try
        {
            baseDao.update("blog_post", post, "id=?", id);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            LOGGER.error("Exception: {}", e);
        }
    }

    @Override
    public void delete(String id)
    {
        baseDao.delete("blog_post", "id=?", id);
    }
}
